<?php
namespace dao;

use common;
use framework\exception\NewException;
use framework\driver\redis;
use framework\driver\constcache;
use framework\driver\mysql;

abstract class DaoBase
{
    /**
     * 动态缓存处理器实例
     *
     * @var \framework\driver\redis\Helper
     */
    protected $cacheHelper;
    /**
     * 静态缓存处理器实例
     *
     * @var \framework\driver\constcache\Helper
     */
    protected $constHelper;
    /**
     * 数据处理器实例
     *
     * @var \framework\driver\mysql\Helper
     */
    protected $pdoHelper;

    /**
     * 实例名称
     *
     * @var string
     */
    protected $entity;
    /**
     * 缓存基础键名
     *
     * @var string
     */
    protected $baseKey;

    /**
     * 构造函数
     *
     * @param string $entity
     */
    public function __construct($entity)
    {
        $this->entity = $entity;

        // 初始化数据处理器
        $this->cacheHelper = new redis\Helper(REDIS_INDEX_CACHE);
        $this->constHelper = new constcache\Helper();
        $this->pdoHelper = new mysql\Helper($entity);
    }

    /**
     * 获取基础键名
     *
     * @return string
     */
    private function getBaseKey()
    {
        if (empty($this->baseKey))
        {
            $items = explode('\\', $this->entity);
            $this->baseKey = implode(KEY_SEPARATOR, array(PROJECT_NAME, end($items)));
        }

        return $this->baseKey;
    }

    /**
     * 获取缓存键名
     *
     * @return string
     */
    protected function getCacheKey()
    {
        $args = func_get_args();
        $keyItems = array($this->getBaseKey());

        if (is_string($args[0]) || is_numeric($args[0]))
        {
            $keyItems[] = $args[0];
        }
        elseif (is_array($args[0]))
        {
            foreach ($args[0] as $key => $value)
            {
                $keyItems[] = $key;
                $keyItems[] = is_array($value) ? implode(KEY_SEPARATOR, $value) : $value;
            }
        }
        elseif (is_object($args[0]) && is_array($args[1]))
        {
            foreach ($args[1] as $key)
            {
                if (property_exists($args[0], $key))
                {
                    $keyItems[] = $key;
                    $keyItems[] = $args[0]->$key;
                }
            }
        }
        else
        {
            throw new NewException(NewException::CODE_ERROR_PARAMS, 'parameterError');
        }

        return implode(KEY_SEPARATOR, $keyItems);
    }

    /**
     * 获取实体的所有属性名称
     *
     * @return array
     */
    protected function getEntityAttribs()
    {
        return array_keys(get_class_vars($this->entity));
    }

    /**
     * 构造SQL字段序列
     *
     * @param int $num
     *
     * @return string
     */
    public function createFileds($num)
    {
        return implode(",", array_fill(0, $num, "?"));
    }
}